<template>
  <div class="home">
    <el-dialog :title="dialogTitle" width="600px" :visible.sync="dialogVisible" :before-close="handleClose">
      <span>
        <el-form :inline="true" :model="addStudent" :rules="rules" ref="addStudent" class="demo-ruleForm" size="mini">
          <el-divider content-position="left">基本信息</el-divider>
          <el-form-item label="学号" prop="snumber">
            <el-input v-model="addStudent.snumber" placeholder="学号" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="addStudent.name" placeholder="姓名" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="classes">
            <el-input v-model="addStudent.classes" placeholder="班级" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="addStudent.sex" style="margin-right: 60px; width: 140px;">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-divider content-position="left">各科成绩</el-divider>
          <el-form-item label="c语言">
            <el-input v-model="addStudent.cscore" placeholder="c语言" style="width: 100px;"></el-input>
          </el-form-item>
          <el-form-item label="java">
            <el-input v-model="addStudent.jscore" placeholder="java" style="width: 100px;"></el-input>
          </el-form-item>
          <el-form-item label="数据库">
            <el-input v-model="addStudent.dbscore" placeholder="数据库" style="width: 100px;"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close" size="mini">取 消</el-button>
        <el-button type="primary" @click="addAndUpdateStudent('addStudent')" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <el-container>
      <el-header>
        <i class="el-icon-edit"></i>简易学生成绩管理系统
        <br/>
      </el-header>
      <el-form :inline="true" :model="addStudent" class="demo-form-inline" size="mini">
        <el-form-item label="学号" :rules="{type: 'number', message: '学号必须为数字值'}">
          <el-input v-model.number="snumber" placeholder="精确查询"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="name" placeholder="模糊查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="reset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="add">录入</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="download">导出学生成绩</el-button>
        </el-form-item>

      </el-form>

      <el-main>
        <el-table :data="studentList" border style="width: 100%" v-if="studentList.length>0">
          <el-table-column fixed prop="snumber" label="学号" min-width="150"></el-table-column>
          <el-table-column prop="name" label="姓名" min-width="150"></el-table-column>
          <el-table-column prop="classes" label="班级" min-width="160"></el-table-column>
          <el-table-column prop="sex" label="性别" min-width="120"></el-table-column>
          <el-table-column prop="cscore" label="c语言成绩" min-width="120"></el-table-column>
          <el-table-column prop="jscore" label="java成绩" min-width="120"></el-table-column>
          <el-table-column prop="dbscore" label="数据库成绩" min-width="120"></el-table-column>
          <el-table-column fixed="right" label="操作" min-width="150">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
              <el-button @click="deleteStudent(scope.row._id || scope.row.id)" type="danger" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="block" v-if="studentList.length>0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[2, 5, 10, 20, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data () {
    return {
      dialogVisible: false, // 对话框是否显示
      dialogTitle: '', // 对话框标题

      // 新增学生
      addStudent: {
        snumber: '', // 学号
        name: '', // 姓名
        classes: '', // 班级
        sex: '', // 性别
        cscore: '', // c语言成绩
        jscore: '', // java成绩
        dbscore: '' // 数据库成绩
      },

      // 学生列表
      // studentList: [{
      //   snumber: '201050092', // 学号
      //   name: '小红', // 姓名
      //   classes: '计算机2班', // 班级
      //   sex: '女', // 性别
      //   cscore: '95', // c语言成绩
      //   jscore: '87', // java成绩
      //   dbscore: '88' // 数据库成绩
      // }],
      studentList: [],

      // 查询关键字
      snumber: '', // 学号
      name: '', // 姓名

      // 分页
      currentPage: 1, // 当前页号
      pageSize: 10, // 每页多少条数据
      total: '', // 总页数

      // 表单验证
      rules: {
        snumber: {required: true, message: '学号不能为空', trigger: 'blur'},
        name: [
          {required: true, message: '姓名不能为空', trigger: 'blur'},
          {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: ['blur', 'change']}
        ],
        classes: [
          {required: true, message: '班级不能为空', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ]
      }
    }
  },
  created () {
    this.getStudentList()
  },
  methods: {
    // 获取学生分页列表
    getStudentList: function () {
      let that = this
      this.$http.get('/getStudentList/?currentPage=' + that.currentPage + '&pageSize=' + that.pageSize).then(result => {
        let data = result.data
        if (data.code === 200) {
          that.studentList = data.msg.data
          that.total = data.msg.total
          // console.log(that.studentList)
        }
      }).catch(function (error) {
        console.log(error)
      })
    },

    // 录入学生信息
    addStudentInfo: function () {
      let that = this
      this.currentPage = 1
      this.$http({
        method: 'post',
        url: '/addStudent',
        data: that.addStudent
      }).then(function (response) {
        let data = response.data
        if (data.code === 200) {
          that.message('录入成功', 'success')
          that.getStudentList()
        } else {
          that.message('录入失败, 学号应独一无二', 'warning')
        }
        // 隐藏录入框
        that.dialogVisible = false
        // 清空录入框信息
        that.addStudent = {}
      })
        .catch(function (error) {
          that.message(error, 'warning')
        })
    },
    // 更新学生信息
    updateStudentInfo: function () {
      let that = this
      let id = this.addStudent._id || this.addStudent.id
      this.$http.put('/updateStudent/' + id, that.addStudent).then(function (response) {
        // console.log(response)
        let data = response.data
        if (data.code === 200) {
          that.message('更新成功', 'success')
          if (that.name === '') {
            that.getStudentList()
          } else {
            that.findByName(that.name)
          }
        } else {
          that.message('更新失败', 'warning')
        }
        // 隐藏录入框
        that.dialogVisible = false
        // 清空录入框信息
        that.addStudent = {}
      })
        .catch(function (error) {
          that.message(error, 'warning')
        })
    },

    // 录入或更新学生信息
    addAndUpdateStudent: function (formName) {
      /*
      if (this.addStudent.snumber === '') {
        this.message('学号不能为空', 'warning')
        return
      }
      if (this.addStudent.name === '') {
        this.message('姓名不能为空', 'warning')
        return
      }
      if (this.addStudent.classes === '') {
        this.message('班级不能为空', 'warning')
        return
      }
      if (this.dialogTitle === '录入学生信息') {
        this.addStudentInfo()
      } else if (this.dialogTitle === '更新学生信息') {
        this.updateStudentInfo()
      }
      */
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === '录入学生信息') {
            this.addStudentInfo()
          } else if (this.dialogTitle === '更新学生信息') {
            this.updateStudentInfo()
          }
        } else {
          // console.log('还有必填项未填')
          return false
        }
      })
    },

    download: function () {
      this.$http.get('/exportToExcel', { responseType: 'blob' }).then(res => {
        console.log(res)
        // const blob = new Blob([res.data], {
        //   type: 'application/octet-stream;charset=utf-8'
        // })
        const blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `学生成绩单_${decodeURI(
          res.headers['content-disposition'].split('_')[1]
        )}`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        // console.log(res.headers['content-disposition'])
      }).catch(function (error) {
        console.log(error)
      })
    },

    // 关闭模态框
    close: function () {
      if (this.dialogTitle === '修改学生信息') {
        this.addStudent = {}
      }
      this.dialogVisible = false
    },

    add: function () {
      this.name = ''
      this.snumber = ''
      this.dialogTitle = '录入学生信息'
      this.dialogVisible = true
    },

    edit: function (data) {
      this.dialogVisible = true
      this.dialogTitle = '更新学生信息'
      this.addStudent = data
      // console.log(this.addStudent)
    },

    // 删除学生信息
    deleteStudent: function (id) {
      console.log(id)
      let that = this
      this.$http.delete('/deleteStudent/' + id).then(function (result) {
        console.log(result)
        let data = result.data
        if (data.code === 200) {
          that.message('删除成功', 'success')
        } else {
          that.message('删除失败', 'warning')
        }
        if (that.name === '') {
          that.getStudentList()
        } else {
          that.findByName(that.name)
        }
      })
        .catch(function (error) {
          that.message(error, 'warning')
        })
    },

    // 根据学号进行精确查询
    findBySnumber: function (snumber) {
      let that = this
      this.$http.get('/findBySnumber/' + snumber).then(result => {
        console.log(result)
        let data = result.data
        if (data.code === 200) {
          that.studentList = data.msg.data
          that.total = 1
        } else {
          that.studentList = []
        }
      }).catch(function (error) {
        console.log(error)
      })
    },

    // 根据姓名进行模糊查询(分页查询)
    findByName: function (name) {
      let that = this
      this.$http.get('/findByName/?name=' + name + '&currentPage=' + that.currentPage + '&pageSize=' + that.pageSize).then(result => {
        let data = result.data
        if (data.code === 200) {
          that.studentList = data.msg.data || []
          that.total = data.msg.total || 0
          // console.log(that.studentList)
        } else {
          that.studentList = []
        }
      }).catch(function (error) {
        console.log(error)
      })
    },

    // 查询
    search: function () {
      if (this.name === '' && this.snumber === '') {
        return
      }
      this.currentPage = 1
      if (this.snumber === '') {
        this.findByName(this.name)
      } else {
        this.findBySnumber(this.snumber)
      }
    },

    // 重置
    reset: function () {
      this.name = ''
      this.snumber = ''
      this.currentPage = 1
      this.getStudentList()
    },

    // 消息通知框
    message: function (msg, mtype) {
      this.$message({
        message: msg,
        type: mtype
      })
    },

    // 关闭模态框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(success => {
          this.addStudent = {}
          this.dialogVisible = false
          console.log('成功')
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 每页多少条
    handleSizeChange (val) {
      this.pageSize = val
      this.getStudentList()
      // console.log(`每页 ${val} 条`)
    },
    // 当前页号
    handleCurrentChange (val) {
      this.currentPage = val
      if (this.name === '') {
        this.getStudentList()
      } else {
        this.findByName(this.name)
      }
      // console.log(`当前页: ${val}`)
    }
  }
}
</script>

<style scoped>
  .el-form{
    text-align: center;
  }
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    text-align: center;
    line-height: 60px;
    margin-bottom: 10px;
  }
  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
    line-height: 30px;
  }
  .block{
    margin-top: 20px;
  }
</style>
